<?php
include 'checkLogin.php';
$allStockPrices = 0;
$income = 0;

@$noPayOrderId = $_REQUEST['noPayOrderId'];
@$payName = $_REQUEST['payName'];
@$payLocation = $_REQUEST['payLocation'];
@$phone = $_REQUEST['phone'];
@$payPrice = $_REQUEST['payPrice'];
@$code = $_REQUEST['code'];

include_once 'db/code.php';

if(!checkCode($code)){
	$mes = '付款失败，验证码错误';
	include 'index.php';
	die;
}

$pdo = new PDO('mysql:dbname=supMkt;charset=UTF8', 'root');

$star = $pdo->prepare('select goodsPrice from `order` where id=:id');
$star->execute(array('id'=>$noPayOrderId));
@$goodsPrice = $star->fetch(PDO::FETCH_NAMED);

if($goodsPrice['goodsPrice'] > $payPrice){			//检查金额
	$mes = '付款失败，请仔细比对金额';
	include 'index.php';
	die;
}
$pdo->beginTransaction();								//事务开始

$star2 = $pdo->prepare('insert into clientele(name,phone,location) value(:name,:phone,:location)');		//添加客户
if($star2->execute(array('name'=>$payName,'phone'=>$phone,'location'=>$payLocation))){
	@$identity = $pdo->prepare("SELECT @@IDENTITY as id;");						//取最近一次客户id
	$identity->execute();
	$id = $identity->fetch();
}

$star4 = $pdo->prepare("select stockPrice from goods_order join goods on goods_order.goodsId=goods.id where goods_order.orderId=:oid");
$star4->execute(array('oid'=>$noPayOrderId));
@$stockPrices = $star4->fetchAll(PDO::FETCH_NAMED);												//查所有进价

foreach ($stockPrices as $price){
	$allStockPrices += $price['stockPrice'];
}
$income = $payPrice - $allStockPrices;				//计算单张订单收入

$star5 = $pdo->prepare("update `order` set payPrice=:payPrice,payDate=now(),pay='是',income=:income,clienteleId=:cId where id=:id");
if($star5->execute(array('payPrice'=>$payPrice,'income'=>$income,'cId'=>$id['id'],'id'=>$noPayOrderId))){	
}else{
	$mes = '付款失败，服务器异常';
	include 'index.php';
	//die;
}
$pdo->commit();								//事务结束

header('Refresh:0;url=orderList.php?orderType=history');




